const fs = require('fs');
const path = require('path');
const { createCanvas, loadImage } = require('canvas');

const sizes = [16, 48, 128];
const inputSvg = path.join(__dirname, 'icons', 'icon.svg');

async function generateIcons() {
  try {
    // 确保icons目录存在
    const iconsDir = path.join(__dirname, 'icons');
    if (!fs.existsSync(iconsDir)) {
      fs.mkdirSync(iconsDir);
    }

    // 为每个尺寸生成PNG图标
    for (const size of sizes) {
      const canvas = createCanvas(size, size);
      const ctx = canvas.getContext('2d');

      // 读取SVG文件内容
      const svgContent = fs.readFileSync(inputSvg, 'utf8');
      const svgDataUrl = `data:image/svg+xml;base64,${Buffer.from(svgContent).toString('base64')}`;

      // 加载SVG并绘制到canvas
      const img = await loadImage(svgDataUrl);
      ctx.drawImage(img, 0, 0, size, size);

      // 保存为PNG
      const outputPath = path.join(iconsDir, `icon${size}.png`);
      const out = fs.createWriteStream(outputPath);
      const stream = canvas.createPNGStream();
      stream.pipe(out);
      await new Promise((resolve, reject) => {
        out.on('finish', resolve);
        out.on('error', reject);
      });

      console.log(`Generated ${size}x${size} icon: ${outputPath}`);
    }

    console.log('All icons generated successfully!');
  } catch (error) {
    console.error('Error generating icons:', error);
  }
}

generateIcons();